package com.yuexunit.mobilenurse.module.Patients.presenter.impl;

import com.alibaba.fastjson.JSON;
import com.yuexunit.mobilenurse.module.PatientDetail.bean.YXPatientSingleBean;
import com.yuexunit.mobilenurse.module.Patients.bean.PatientList_Patinfo;
import com.yuexunit.mobilenurse.module.Patients.bean.YXPatientListBean;
import com.yuexunit.mobilenurse.module.Patients.model.IPatientListModel;
import com.yuexunit.mobilenurse.module.Patients.model.impl.PatientListModel;
import com.yuexunit.mobilenurse.module.Patients.presenter.IPatientListPresenter;
import com.yuexunit.mobilenurse.module.Patients.ui.fragment.Frag_PatientList_Normal;
import com.yuexunit.mobilenurse.module.Patients.ui.view.IPatientListView;
import com.yuexunit.mobilenurse.module.SignInput.bean.All_Sqlite_SignInputBean;
import com.yuexunit.mobilenurse.module.SignInput.bean.SignsInput_Data;
import com.yuexunit.mobilenurse.module.SignInput.xml.SignInputXML;

import org.json.JSONException;
import org.json.JSONObject;
import org.kymjs.kjframe.ui.ViewInject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.UnknownHostException;
import java.util.ArrayList;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by sslcjy on 16/1/22.
 */
public class PatientListPresenter implements IPatientListPresenter {

    private IPatientListModel model;
    private IPatientListView view;
    //病人列表
    ArrayList<PatientList_Patinfo> patientList = new ArrayList<PatientList_Patinfo>();
    //记录Log
    private final Logger log = LoggerFactory.getLogger(PatientListModel.class);

    public CompositeSubscription compositeSubscription = new CompositeSubscription();

    public PatientListPresenter(IPatientListModel model, IPatientListView view) {
        this.model = model;
        this.view = view;
    }

    @Override
    public void oneKeyUpload(final ArrayList<All_Sqlite_SignInputBean> list) {
        if(!(list.size() >0)){
            ViewInject.toast("未有需要上传的体征数据信息...");
            return;
        }
        String content = "";
        for (final All_Sqlite_SignInputBean sqlite_signInputBean : list) {
            content +=sqlite_signInputBean.getSignData();
        }

        model.uploadTypesValueXML(content).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<String>() {
                        @Override
                        public void onCompleted() {
                            log.info("PatientListPresenter_oneKeyUpload_onCompleted");
                        }

                        @Override
                        public void onError(Throwable e) {
                            ViewInject.toast("一键上传体征信息失败");
                            log.info("PatientListPresenter_oneKeyUpload_onError:"+e);
                        }

                        @Override
                        public void onNext(String s) {
                            String msg = SignInputXML.getErrorMsg(s);
                            view.oneKeyUploadXml(msg,list);
                        }
                    });

    }

    @Override
    public void showPatientList(String Wardno) {
        model.getPatientListData(Wardno)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber() {
                    @Override
                    public void onCompleted() {
                        log.info("PatientListPresenter_showPatientList_onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                        log.error("PatientListPresenter_showPatientList_onError:" + e);
                        if (e instanceof UnknownHostException) {
                            view.PullDownRefreshState(Frag_PatientList_Normal.DOWNLOAD_NETERROR);
                        } else {
                            view.PullDownRefreshState(Frag_PatientList_Normal.DOWNLOAD_NODATA);
                        }
                    }

                    @Override
                    public void onNext(Object response) {
                        JSONObject all, body;
                        String result = null;
                        try {
                            all = new JSONObject(response.toString());
                            body = all.getJSONObject("body");
                            result = body.getString("response");
                            log.info("PatientListPresenter_showPatientList_onNext_response:"+response);
                        } catch (JSONException e) {
                            log.error("showPatientList_JSONException:"+e);
                        }
                        if (!("null".equals(result))) {
                            try {
                                YXPatientSingleBean Total = JSON.parseObject(response.toString(), YXPatientSingleBean.class);
                                YXPatientSingleBean listBean = Total.getBody();
                                if ("0".equals(listBean.getHead().getRet_code())) {
                                    PatientList_Patinfo patientList_patinfo = new PatientList_Patinfo();
                                    patientList_patinfo = listBean.getResponse().getPatinfo();
                                    patientList.clear();
                                    patientList.add(patientList_patinfo);
                                } else {
                                    ViewInject.toast("获取病人列表失败：" + listBean.getHead().getRet_info());
                                }
                            } catch (Exception e) {
                                YXPatientListBean Total = JSON.parseObject(response.toString(), YXPatientListBean.class);
                                YXPatientListBean listBean = Total.getBody();
                                if ("0".equals(listBean.getHead().getRet_code())) {
                                    patientList = listBean.getResponse().getPatinfo();
                                } else {
                                    ViewInject.toast("获取病人列表失败：" + listBean.getHead().getRet_info());
                                }
                            }
                            if (patientList != null) {
                                log.info("PatientListPresenter_showPatientList_onNext_patientList.size():"+patientList.size());
                                view.showPatientList(patientList);
                                view.PullDownRefreshState(Frag_PatientList_Normal.DOWNLOAD_SUCCESS);
                            }
                        } else {
                            view.PullDownRefreshState(Frag_PatientList_Normal.DOWNLOAD_NODATA);
                        }
                    }
                });
    }

    @Override
    public void getBaseTypes(String areaId) {
        compositeSubscription.add(
                model.getBaseTypes(areaId)
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Subscriber<ArrayList<SignsInput_Data>>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {
                                e.printStackTrace();
                            }

                            @Override
                            public void onNext(ArrayList<SignsInput_Data> signsInput_datas) {
                                view.saveBaseTypes(signsInput_datas);
                            }
                        }));

    }

    @Override
    public void getAllTypes() {
        compositeSubscription.add(
                model.getAllTypes()
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Subscriber<ArrayList<SignsInput_Data>>() {
                            @Override
                            public void onCompleted() {
                            }

                            @Override
                            public void onError(Throwable e) {
                                e.printStackTrace();
                            }

                            @Override
                            public void onNext(ArrayList<SignsInput_Data> signsInput_datas) {
                                view.saveAllTypes(signsInput_datas);
                            }
                        }));
    }
}
